
/**小程序buyer login相关**/

package oauth

import (
    "fmt"
	"encoding/json"
	"wxsdk/miniapp/core"
	"wxsdk/miniapp/utils/security"
	//"github.com/astaxie/beego"
)

type SessionInfo struct {
   OpenId     string `json:"openid"` 
   SessionKey string `json:"session_key"`   
   UnionId    string `json:"unionid"` 
}

// 第三方平台代替小程序实现登录(代管登陆)
func JsCode2Session(appId, isvAppId,isvAccessToken,code string)(info *SessionInfo, err error){
	var result struct {
		core.Error
		SessionInfo
	}
	client := core.GetPostJSONClient()
	serverUrl := fmt.Sprintf("https://api.weixin.qq.com/sns/component/jscode2session?appid=%s&js_code=%s&grant_type=authorization_code&component_appid=%s&component_access_token=%s",appId,code,isvAppId,isvAccessToken)
	if _, err = client.Excute("POST", serverUrl, nil, &result); err != nil {
		return
	}
	if result.ErrCode != core.ErrCodeOK {
		err = &result.Error
		return
	}
	info = &result.SessionInfo
	return
}

// 自管小程序实现登录
func  JsCode2SessionOwn(appId, secret, code string)(info *SessionInfo, err error){
	var result struct {
		core.Error
		SessionInfo
	}
	client := core.GetPostJSONClient()
	serverUrl := fmt.Sprintf("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",appId,secret,code)
	_, e := client.Excute("GET", serverUrl, nil, &result)
	if e != nil {
		err = e
		return 
	}
	//beego.Debug("tbData:", string(tbData))
	if result.ErrCode != core.ErrCodeOK {
		err = &result.Error
		return
	}
	info = &result.SessionInfo
	return
}

//解密小程序加密信息
type DecryptedUserInfo struct {
	*core.ErrorResponse
	OpenID         string    `json:"openId"`             
	NickName       string    `json:"nickName"`             
	Gender         int       `json:"gender"`              
	City           string    `json:"city"`            
	Province       string    `json:"province"`
	Country        string    `json:"country"`
	AvatarURL      string    `json:"avatarUrl"`
	UnionId        string    `json:"unionId"`
	WaterMark                `json:"watermark"`
}

func DecryptedAppUserInfo(sessionKey,encryptedData,iv string)(info *DecryptedUserInfo, err error){
	decrypted, e := security.WXBizDataDecrypt(sessionKey,encryptedData,iv)
	if e != nil {
		err = e
		return
	}
	info = new(DecryptedUserInfo)
	if err = json.Unmarshal(decrypted, info); err != nil {
	    return
	}
	return
}

